<?php
//------------------------
// 订单模型
//-------------------------
namespace app\common\model;

use think\Model;
use think\Db;
use think\Session;
use think\Cookie;
use constant\OrderStatus;
use constant\PayStatus;
use constant\ShippingStatus;

class Order extends Model{

	// 下单
	public function placeOrder($data){
		$address = Db('UserAddress')->where('id',$data['address_id'])->find();

		$cartModle = model('Cart');
		$cartInfo = $cartModle->getCartInfo();
        $res = $cartModle->getCartToBuyThis($cartInfo,Session::get('buythis'));

        $total_amount = $res['totalPrice'];//订单总价
        $shipping_price = 0;//邮费
        $actual_price = $total_amount + $shipping_price;//应付价钱
        $order_goods  = $res['info'];
        $order_sn     = $this->generateOrder();

        // halt($actual_price);

		$this->data([
			'order_status'    =>  OrderStatus::TO_BE_CONFIRMED,
			'shipping_status' =>  ShippingStatus::NOT_SHIPPED,
			'pay_status'      =>  PayStatus::UNPAID,
			'order_sn'        =>  $order_sn,
			'total_amount'    =>  $total_amount,
			'actual_price'    =>  $actual_price,
			'user_id'         =>  $address['user_id'],
			'consignee'       =>  $address['consignee'],
			'province'        =>  $address['province'],
			'city'            =>  $address['city'],
			'area'            =>  $address['area'],
			'addr'            =>  $address['addr'],
			'zipcode'         =>  $address['zipcode'],
			'mobile'          =>  $address['mobile'],
			'user_remark'     =>  $data['user_remark'],
			'invoice_title'   =>  $data['invoice_title'],
			'add_time'        =>  time()
		]);
		$this->save();

		$order_id = $this->id;

		// 生成插入商品订单表数组
		$addData = array();
		$i = 0;
		foreach ($order_goods as $k => $v) {
			$addData[$i]['order_id'] = $order_id;
			$addData[$i]['goods_id'] = $v['goods_id'];
			$addData[$i]['user_id'] = $v['user_id'];
			$addData[$i]['quantity'] = $v['quantity'];
			$addData[$i]['price'] = $v['price'];
			$addData[$i]['spec_key'] = $v['goods_spec_key'];
			$addData[$i]['spec_key_name'] = $v['spec_details'];
			$i = ++$i;
		}

		// halt($addData);

		Db('orderGoods')->insertAll($addData);

		// 清空购物车中勾选了的商品
		$cartModle->clearBuythis();

		// 返回订单id
		return $order_id;

	}

	// 生成一个随机订单号
	public function generateOrder(){
		return $order_sn = 'sf_order_' . date('YmdHis') . rand(1000, 9999);//订单号
	}


}